<template>
  <el-dialog
    v-model="dialogVisible"
    title="创建用户特定价格"
    width="500px"
    @close="resetForm"
  >
    <el-form ref="serviceForm" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="价格" prop="price">
        <el-input-number v-model="form.price" class="!w-[260px]" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" :loading @click="handleConfirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { createUserPrice } from "@/api/adminPriceApi";
import { message } from "@/utils/message";
const dialogVisible = ref(false);
const loading = ref(false);
const emits = defineEmits(["refresh"]);
const form = ref({
  price: 0
});
const standardCode = ref("");
const userId = ref(0);
// 基础校验规则
const rules = {
  price: [
    { required: true, message: "请输入价格", trigger: "blur" },
    {
      pattern: /^[-+]?(\d+(\.\d+)?|\.\d+)$/,
      message: "请输入正确的数字",
      trigger: "blur"
    },
    {
      validator: (rule, value, callback) => {
        if (value <= 0) {
          callback(new Error("价格必须大于0"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
};

const serviceForm = ref(null);
// 重置表单
const resetForm = () => {
  serviceForm.value?.resetFields();
};

const handleConfirm = () => {
  serviceForm.value.validate(async valid => {
    if (valid) {
      try {
        loading.value = true;
        await createUserPrice(userId.value, standardCode.value, form.value);
        message("创建成功", { type: "success" });
        emits("refresh");
        dialogVisible.value = false;
      } catch (error) {
        console.log(error);
      } finally {
        loading.value = false;
      }
    }
  });
};
const open = (row: {
  userId: number;
  standardCode: string;
  customPrice?: number;
}) => {
  standardCode.value = row.standardCode;
  userId.value = row.userId;
  form.value.price = row.customPrice ?? 0;
  dialogVisible.value = true;
};
defineExpose({
  open
});
</script>
